// 问答逻辑
document.getElementById("imageChatForm").addEventListener("submit", async function(e) {
  e.preventDefault();
  const imageFileInput = document.getElementById("imageFile");
  const imageFile = imageFileInput.files[0];
  const question = document.getElementById("imageQuestion").value.trim();

  if (!question) return alert("请输入问题内容");

  appendMessage("user", question); // 添加用户消息

  const formData = new FormData();
  formData.append("question", question);
  if (imageFile) {
    formData.append("image", imageFile);
  }

  // 先创建一个空的 bot 消息气泡，用于流式更新
  const botMessageElement = appendMessage("bot", "");

  try {
    const res = await fetch("http://localhost:8000/chat/", {
      method: "POST",
      body: formData
    });

    const reader = res.body.getReader();
    const decoder = new TextDecoder("utf-8");

    let isReasoning = false; // 判断是否正在输出思考部分
    let flag = 1; // flag为1时为思考内容，为0时为内容
    let flag_content = 1;
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });

      // 判断流中的标签，分别处理思考内容和答案内容
      if (chunk.startsWith("[REASON]")) {
          flag = 1
      } else if (chunk.startsWith("[ANSWER]")) {
        isReasoning = false;
        flag = 0
      }
      // 思考方式
      if (flag === 1) {
          if (!isReasoning) {
          isReasoning = true;
          updateLastBotMessage(botMessageElement, "思考过程：\n", "reason");
          }
          updateLastBotMessage(botMessageElement, chunk.replace("[REASON]", ""), "reason");
      }
      else if(flag === 0) {
          if (flag_content === 1){
              updateLastBotMessage(botMessageElement, "\n 回答： \n", "answer");
              flag_content = 0;
          }
          else{
              updateLastBotMessage(botMessageElement, "", "answer");
          }
          updateLastBotMessage(botMessageElement, chunk.replace("[ANSWER]", ""), "answer");
      }
    }
  } catch (err) {
    updateLastBotMessage(botMessageElement, "请求失败：" + err.message);
  }

  // 清空输入框
  document.getElementById("imageQuestion").value = "";
  imageFileInput.value = "";
});

// 创建气泡并返回消息 DOM 元素，供更新用
function appendMessage(sender, text) {
  const chatBox = document.getElementById("chatBox");
  const wrapper = document.createElement("div");
  wrapper.className = sender === "user" ? "text-right" : "text-left";

  const bubble = document.createElement("div");
  bubble.className = "inline-block px-4 py-2 rounded-2xl max-w-[70%] text-sm whitespace-pre-wrap " +
    (sender === "user" ? "bg-indigo-600 text-white" : "bg-gray-200 text-gray-800");

  bubble.textContent = text;
  wrapper.appendChild(bubble);
  chatBox.appendChild(wrapper);
  chatBox.scrollTop = chatBox.scrollHeight;

  return bubble; // 返回 bubble，用于后续更新
}

// 在已有气泡中追加内容
function updateLastBotMessage(bubbleElement, newText, type = "") {
  const span = document.createElement("span");

  if (type === "reason") {
    span.className = "text-blue-600"; // 蓝色表示思考部分
  } else if (type === "answer") {
    span.className = "text-green-600"; // 绿色表示回答部分
  }

  // {#span.textContent = newText;#}
  // {#bubbleElement.appendChild(span);#}
  const html = marked.parseInline(newText); // 不会包裹 <p>
  span.innerHTML = html;
  bubbleElement.appendChild(span);
}



// 报告上传逻辑
document.getElementById("uploadForm").addEventListener("submit", async function(e) {
  e.preventDefault();
  const doc = document.getElementById("docFile").files[0];
  const excel = document.getElementById("excelFile").files[0];
  if (!doc || !excel) return alert("请上传Word和Excel文件");

  const formData = new FormData();
  formData.append("word", doc);
  formData.append("excel", excel);

  try {
    const res = await fetch("http://localhost:8000/doc/", {
      method: "POST",
      body: formData
    });

    if (res.ok) {
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const downloadLink = document.getElementById("downloadLink");
      downloadLink.href = url;
      downloadLink.download = "义务教育质量监测报告.docx";
      document.getElementById("reportStatus").classList.remove("hidden");
    } else {
      alert("报告生成失败");
    }
  } catch (err) {
    alert("上传失败：" + err.message);
  }
});